﻿using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Newtonsoft.Json;
using Power.Models;
using Power.View;
using Power.View.Dialog;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;

namespace Power.ViewModel
{
    public class TestRecordViewModel : BaseModel
    {
       
        private TestRecord model;
        public TestRecordViewModel(TestRecord model)
        {
            this.model = model;
            this.model.page.PageUpdated += Page_PageUpdated;
            model.grid.CellEditEnding += Grid_CellEditEnding;

            model.grid.PreviewKeyDown += Grid_PreviewKeyDown;
            //model.grid.SelectionChanged += Grid_SelectionChanged; 

            Delete = new RelayCommand(OnDelete);
            ShowDialog = new RelayCommand(OnShowDialog);
            OpenSelect = new RelayCommand(OnOpenSelect);
            CheckBoxClick = new RelayCommand<int>(OnCheckBoxClick);
            ColumnCheckBox = new RelayCommand<ColumnListItem>(OnColumnCheckBox);
            ShowImageDetail = new RelayCommand<string>(OnShowImageDetail);
            Data = new ObservableCollection<DetectRecordEntity>()
            {
                new DetectRecordEntity()
                {
                    ID = 1,
                    Area = "区域",
                    Block = "区块",
                    WorkField= "工点",
                    StartWell = new WellEntity()
                    {
                        No = "2",
                        Type = "1",
                        FuncType = "1",
                        Mat = "1",
                        Problem = "1",

                    },
                    EndWell = new WellEntity()
                    {

                        No = "2",
                        Type = "1",
                        FuncType = "1",
                        Mat = "1",
                        Problem = "1",
                    },
                    Defect = new DefectEntity()
                    {
                        No = 1,
                        Type = "1",
                        Name = "1",
                        Level = 1,
                        Length = 1,
                        CircleDirection = "1",
                        DetectDate = "1",
                        StartPos = 1,
                        EndPos = 1,
                        Code = "1",
                        Describe = "1",
                        PicUri="/Resources/images/ais1.png"
                    },
                    Detect = new DetectEntity() { 
                        Length = 1,
                        Method = "1",
                        Direction = "1",
                        Date = "1",
                        Batch = 1,
                        Detector = "1",
                        Subcontractors = "1",
                        PicName = "1",
                        Describe = "1",
                        WorkGroup = "1",
                        CollectDetector = "1"
                    },
                    Pip = new PipEntity()
                    {
                        No = 1,
                        BeginBuriedDepth = 1,
                        EndBuriedDepth =9,
                        Type = "1",
                        Mat = "1",
                        Diameter = 1,
                        Length = 1,
                        AreaParam = "1",
                        SolidParam = "1",
                        BuildDate = "1",


                    }
                },
                new DetectRecordEntity()
                {
                    ID = 2,
                    Area = "区域",
                    Block = "区块",
                    WorkField= "工点",
                    StartWell = new WellEntity()
                    {
                        No = "2",
                        Type = "1",
                        FuncType = "1",
                        Mat = "1",
                        Problem = "1",

                    },
                    EndWell = new WellEntity()
                    {

                        No = "2",
                        Type = "1",
                        FuncType = "1",
                        Mat = "1",
                        Problem = "1",
                    },
                    Defect = new DefectEntity()
                    {
                        No = 1,
                        Type = "1",
                        Name = "1",
                        Level = 1,
                        Length = 1,
                        CircleDirection = "1",
                        DetectDate = "1",
                        StartPos = 1,
                        EndPos = 1,
                        Code = "1",
                        Describe = "1",
                        PicUri="/Resources/images/defects.png"
                    },
                    Detect = new DetectEntity() {
                        Length = 1,
                        Method = "1",
                        Direction = "1",
                        Date = "1",
                        Batch = 1,
                        Detector = "1",
                        Subcontractors = "1",
                        PicName = "1",
                        Describe = "1",
                        WorkGroup = "1",
                        CollectDetector = "1"
                    },
                    Pip = new PipEntity()
                    {
                        No = 1,
                        BeginBuriedDepth = 1,
                        EndBuriedDepth =9,
                        Type = "1",
                        Mat = "1",
                        Diameter = 1,
                        Length = 1,
                        AreaParam = "1",
                        SolidParam = "1",
                        BuildDate = "1",
                    }
}
            };
            //片区
            AreaSelectList = Common.Common.GetAreaSelectList();
            //区块
            BlockSelectList = Common.Common.GetBlockSelectList();
            //工点
            WorkSelectList = Common.Common.GetWorkSelectList();
            //管道
            BatchSelectList = Common.Common.GetBatchSelectList();
            //批次
            PipSelectList = Common.Common.GetPipSelectList();
            //缺陷类型
            DefectTypeSelectList = Common.Common.GetDefectTypeSelectList();
            //缺陷等级
            DefectLevelSelectList = Common.Common.GetDefectLevelSelectList();
            DetectRecordSearchEntity = new DetectRecordSearchEntity() {
                ID = -1,//标记
                StartWell = new WellEntity() { Type = "0", FuncType="0", Mat="0", Problem="0" },
                EndWell = new WellEntity() { Type = "0", FuncType = "0", Mat = "0", Problem = "0" },   
                Pip = new PipEntity() { Type="0", Mat = "0" },
                Defect = new DefectEntity() { Type = "0", Name="0" },
                Detect = new DetectEntity() { Direction="0", Method="0" }
            };
            ColumnList = new ObservableCollection<ColumnListItem>() {
                    new ColumnListItem(){IsChecked=true,ColumnName="全部"},
                    new ColumnListItem(){IsChecked=true,ColumnName="序号"},
                    new ColumnListItem(){IsChecked=true,ColumnName="片区"},
                    new ColumnListItem(){IsChecked=true,ColumnName="区块"},
                    new ColumnListItem(){IsChecked=true,ColumnName="工点名称"},
                    new ColumnListItem(){IsChecked=true,ColumnName="起始井号"},
                    new ColumnListItem(){IsChecked=true,ColumnName="起始井类型"},
                    new ColumnListItem(){IsChecked=true,ColumnName="起始井功能类型"},
                    new ColumnListItem(){IsChecked=true,ColumnName="起始井材质"},
                    new ColumnListItem(){IsChecked=true,ColumnName="起始井内外部检查"},
                    new ColumnListItem(){IsChecked=true,ColumnName="是否在道路上"},

                    new ColumnListItem(){IsChecked=true,ColumnName="终止井号"},
                    new ColumnListItem(){IsChecked=true,ColumnName="终止井类型"},
                    new ColumnListItem(){IsChecked=true,ColumnName="终止井功能类型"},
                    new ColumnListItem(){IsChecked=true,ColumnName="终止井材质"},
                    new ColumnListItem(){IsChecked=true,ColumnName="终止井内外部检查"},
                    new ColumnListItem(){IsChecked=true,ColumnName="是否在道路上"},

                    new ColumnListItem(){IsChecked=true,ColumnName="地区参数"},
                    new ColumnListItem(){IsChecked=true,ColumnName="土质参数"},
                    new ColumnListItem(){IsChecked=true,ColumnName="敷设年代"},
                    new ColumnListItem(){IsChecked=true,ColumnName="管段类型"},
                    new ColumnListItem(){IsChecked=true,ColumnName="管段材质"},
                    new ColumnListItem(){IsChecked=true,ColumnName="管段直径"},
                    new ColumnListItem(){IsChecked=true,ColumnName="管段长度"},
                    new ColumnListItem(){IsChecked=true,ColumnName="检测长度"},
                    new ColumnListItem(){IsChecked=true,ColumnName="起点埋深"},
                    new ColumnListItem(){IsChecked=true,ColumnName="终点埋深"},
                    new ColumnListItem(){IsChecked=true,ColumnName="检测方法"},
                    new ColumnListItem(){IsChecked=true,ColumnName="检测方向"},
                    new ColumnListItem(){IsChecked=true,ColumnName="缺陷起始位置"},
                    new ColumnListItem(){IsChecked=true,ColumnName="缺陷终止位置"},
                    new ColumnListItem(){IsChecked=true,ColumnName="环向"},
                    new ColumnListItem(){IsChecked=true,ColumnName="缺陷类型"},
                    new ColumnListItem(){IsChecked=true,ColumnName="缺陷名称"},
                    new ColumnListItem(){IsChecked=true,ColumnName="缺陷代码"},
                    new ColumnListItem(){IsChecked=true,ColumnName="缺陷等级"},
                    new ColumnListItem(){IsChecked=true,ColumnName="检测图片"},
                    new ColumnListItem(){IsChecked=true,ColumnName="检测描述"},
                    new ColumnListItem(){IsChecked=true,ColumnName="检测日期"},
                    new ColumnListItem(){IsChecked=true,ColumnName="检测批次"},
                    new ColumnListItem(){IsChecked=true,ColumnName="数据采集人员"},
                    new ColumnListItem(){IsChecked=true,ColumnName="数据解释人员"},
                    new ColumnListItem(){IsChecked=true,ColumnName="作业组"},
                    new ColumnListItem(){IsChecked=true,ColumnName="分包商"}
            };
        }

        private void Page_PageUpdated(object sender, HandyControl.Data.FunctionEventArgs<int> e)
        {
            var currentPage = e.Info;
        }

        private void OnShowImageDetail(string imageUrl)
        {
            if (!string.IsNullOrWhiteSpace(imageUrl)) { 
                ImagesDetail box = new ImagesDetail(imageUrl);
                box.ShowDialog();
            }
        }

        private void OnCheckBoxClick(int obj)
        {
            var item = Data.Where(p => p.ID == obj).FirstOrDefault();
            if (item != null)
            {
                item.IsSelectedFlag = !item.IsSelectedFlag;
            }
            //var item = obj as PipManaEntity;
            //if (item != null && item.IsSelectedFlag)
            //{ 
            //    this.model.SectionDataGrid1.SelectedItems.Remove(item);
            //}
        }

        private void Grid_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            foreach (var item in Data)
            {
                item.IsSelectedFlag = false;
            }
            var selectedList = this.model.grid.SelectedItems;
            if (selectedList != null || selectedList.Count > 0)
            {
                for (int i = 0; i < selectedList.Count; i++)
                {
                    var item = selectedList[i] as DetectRecordEntity;
                    item.IsSelectedFlag = true;
                }
            }
        }

        private void Grid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Delete)
            {
                e.Handled = true;

                DeleteSelectedItems();
            }
        }

        private void Grid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
        {
            if (e.EditingElement is TextBox)
            {
                string newValue = (e.EditingElement as TextBox).Text;
                var item = this.model.grid.SelectedItem as DetectRecordEntity;
                if (item != null)
                {
                    DetectRecordEntity dataItem = data.FirstOrDefault(a => a.ID == item.ID);
                    string[] arr = e.Column.SortMemberPath.Split('.');
                    //二级关联属性
                    var tModel = dataItem.GetType().GetProperty(arr[0]).GetValue(dataItem,null);
                    var tPro = tModel.GetType().GetProperty(arr[1]);
                    var oldValue = Convert.ToString(tPro.GetValue(tModel, null));
                    if (oldValue != newValue) {
                        //判断数据类型
                        if (tPro.PropertyType.Equals(typeof(int)) )
                        {
                            int v;
                            if (int.TryParse(newValue, out v))
                            {
                                tPro.SetValue(tModel,v);
                            }
                            else
                            {
                                tPro.SetValue(tModel, 0);
                            }
                            
                        }
                        else if (tPro.PropertyType.Equals(typeof(double)))
                        {
                            double v;
                            if (double.TryParse(newValue, out v))
                            {
                                tPro.SetValue(tModel, v);
                            }
                            else
                            {
                                tPro.SetValue(tModel, 0);
                            }
                            tPro.SetValue(tModel, Convert.ToDouble(newValue));
                        }
                        else {
                            tPro.SetValue(tModel, newValue);
                        }

                        MessagePrompt box = new MessagePrompt("更新成功");
                        box.ShowDialog();
                    }
                }
            }
        }
        private void OnDelete()
        {
            DeleteSelectedItems();
        }
        public void DeleteSelectedItems()
        {
            //var selectedList = this.model.grid.SelectedItems;
            var selectedList = this.Data.Where(p => p.IsSelectedFlag == true).ToList();
            if (selectedList == null || selectedList.Count == 0)
            {
                MessagePrompt box = new MessagePrompt("请选择要删除的行");
                box.ShowDialog();
                return;
            }
            {
                MessagePrompt box = new MessagePrompt("是否确认删除？", true);
                var result = box.ShowDialog();
                if (result == true)
                {
                    for (int i = 0; i < selectedList.Count; i++)
                    {
                        var item = selectedList[i] as DetectRecordEntity;
                        Data.Remove(item);
                        //i--;
                    }
                }
            }
        }
        private void OnColumnCheckBox(ColumnListItem curitem)
        {
            int index = ColumnList.IndexOf(curitem);
            if (index == 0)
            {
                foreach (var item in ColumnList)
                {
                    item.IsChecked = curitem.IsChecked;
                }
            }
            else
            {
                var first = ColumnList.FirstOrDefault();
                var list = ColumnList.Where(a => a != first).ToList();
                if (list.Where(a => a.IsChecked).Count() == list.Count)
                {
                    first.IsChecked = true;
                }
                else
                {
                    first.IsChecked = false;
                }
            }
        }

        private void OnOpenSelect()
        {
            this.model.selectPopup.IsOpen = true;
        }

        /// <summary>
        /// 更多条件弹窗
        /// </summary>
        private void OnShowDialog()
        {

            string json = JsonConvert.SerializeObject(this.DetectRecordSearchEntity);
            //弹出消息框
            TestRecordP1 box = new TestRecordP1(ref this.DetectRecordSearchEntity);
            var flag = box.ShowDialog();
            if (flag == true)
            {
                //点击了确认，重新根据条件查询数据
                var model = this.DetectRecordSearchEntity;
            }
            else {
                this.DetectRecordSearchEntity = JsonConvert.DeserializeObject<DetectRecordSearchEntity>(json);
            }
        }

        private DetectRecordEntity selectedItem;
        private bool checkBoxIsChecked;

        public bool CheckBoxIsChecked
        {
            get
            {
                return checkBoxIsChecked;
            }
            set
            {
                checkBoxIsChecked = value;
                ChangedSelecgedFlags();
                RaisePropertyChanged();
                RaisePropertyChanged("Data");
            }
        }

        public DetectRecordEntity SelectedItem
        {
            get
            {
                return selectedItem;
            }
            set
            {
                selectedItem = value;
                RaisePropertyChanged();
            }
        }

        #region 数据实体
        private ObservableCollection<DetectRecordEntity> data;
        public ObservableCollection<DetectRecordEntity> Data
        {
            get
            {
                return data;
            }
            set
            {
                data = value;
                RaisePropertyChanged();
            }
        }

        public ObservableCollection<DetectRecordEntity> Data2;

        //片区
        private List<SelectListItem> areaSelectList;
        public List<SelectListItem> AreaSelectList
        {
            get => areaSelectList;
            set
            {
                areaSelectList = value;
                RaisePropertyChanged();
            }
        }

        //区块
        private List<SelectListItem> blockSelectList;
        public List<SelectListItem> BlockSelectList
        {
            get => blockSelectList;
            set
            {
                blockSelectList = value;
                RaisePropertyChanged();
            }
        }

        //工点
        private List<SelectListItem> workSelectList;
        public List<SelectListItem> WorkSelectList
        {
            get => workSelectList;
            set
            {
                workSelectList = value;
                RaisePropertyChanged();
            }
        }

        //批次
        private List<SelectListItem> batchSelectList;
        public List<SelectListItem> BatchSelectList
        {
            get => batchSelectList;
            set
            {
                batchSelectList = value;
                RaisePropertyChanged();
            }
        }

        //管道
        private List<SelectListItem> pipSelectList;
        public List<SelectListItem> PipSelectList
        {
            get => pipSelectList;
            set
            {
                pipSelectList = value;
                RaisePropertyChanged();
            }
        }

        //缺陷类型
        private List<SelectListItem> defectTypeSelectList;
        public List<SelectListItem> DefectTypeSelectList
        {
            get => defectTypeSelectList;
            set
            {
                defectTypeSelectList = value;
                RaisePropertyChanged();
            }
        }

        public DetectRecordSearchEntity DetectRecordSearchEntity;
        //缺陷等级
        private List<SelectListItem> defectLevelSelectList;
        public List<SelectListItem> DefectLevelSelectList
        {
            get => defectLevelSelectList;
            set
            {
                defectLevelSelectList = value;
                RaisePropertyChanged();
            }
        }

        /// <summary>
        /// 列名
        /// </summary>
        private ObservableCollection<ColumnListItem> columnList;
        public ObservableCollection<ColumnListItem> ColumnList
        {
            get => columnList;
            set
            {
                columnList = value;
                RaisePropertyChanged();
            }
        }
       
        #endregion


        private void ChangedSelecgedFlags()
        {
            if (CheckBoxIsChecked == false)
            {
                foreach (var e in Data)
                    e.IsSelectedFlag = false;
            }
            else
            {
                foreach (var e in Data)
                    e.IsSelectedFlag = true;
            }

            //if (checkBoxIsChecked)
            //{
            //    this.model.grid.SelectedItems.Clear();
            //    foreach (var item in this.model.grid.Items)
            //    {
            //        this.model.grid.SelectedItems.Add(item);
            //    }
            //}
            //else
            //{
            //    this.model.grid.SelectedItems.Clear();
            //}
        }



        public int PageIndex { get; set; } = 1;

        #region 
        public RelayCommand ShowDialog { get; private set; }
        public RelayCommand OpenSelect { get; private set; }
        public RelayCommand<int> CheckBoxClick { get; private set; }
        public RelayCommand<string> ShowImageDetail { get;private set;  }
        public RelayCommand Delete { get; private set; }
        public RelayCommand<ColumnListItem> ColumnCheckBox { get; private set; }
        #endregion
    }
}
